"""
SDP-PY: Standard Directory Project Generator for Python
Python项目标准目录结构生成器

主程序入口文件
"""

import click
from pathlib import Path
from typing import Optional
from rich.console import Console
from rich.table import Table
from rich.panel import Panel
from rich.text import Text
from loguru import logger

from core import ProjectGenerator, ProjectConfig, TemplateManager
from core.config import ConfigManager

# 设置控制台
console = Console()

# 配置日志
logger.remove()
logger.add(
    "logs/sdp.log",
    rotation="10 MB",
    retention="30 days",
    level="INFO",
    format="{time:YYYY-MM-DD HH:mm:ss} | {level} | {message}"
)


@click.group()
@click.version_option(version="0.1.0")
@click.option('--verbose', '-v', is_flag=True, help='启用详细输出')
def cli(verbose: bool):
    """
    SDP-PY: Python项目标准目录结构生成器
    
    快速生成标准化的Python项目结构，支持多种项目类型。
    """
    if verbose:
        logger.add(lambda msg: console.print(f"[dim]{msg}[/dim]"), level="DEBUG")


@cli.command()
@click.argument('project_name')
@click.option('--type', '-t', 'project_type', 
              type=click.Choice(['fastapi', 'fastmcp']), 
              default='fastapi', help='项目类型')
@click.option('--author', '-a', default='Clark', help='作者姓名')
@click.option('--email', '-e', default='changhongyuan@126.com', help='作者邮箱')
@click.option('--description', '-d', help='项目描述')
@click.option('--target-dir', default='.', help='目标目录')
@click.option('--no-git', is_flag=True, help='不初始化Git仓库')
@click.option('--no-uv', is_flag=True, help='不初始化uv项目')
@click.option('--config', '-c', type=click.Path(exists=True), help='从配置文件加载设置')
def generate(
    project_name: str,
    project_type: str,
    author: str,
    email: str,
    description: Optional[str],
    target_dir: str,
    no_git: bool,
    no_uv: bool,
    config: Optional[str]
):
    """
    生成新的Python项目
    
    PROJECT_NAME: 项目名称，只能包含字母、数字、连字符和下划线
    """
    
    # 验证项目名称
    if not ConfigManager.validate_project_name(project_name):
        console.print("[bold red]❌ 项目名称无效！[/bold red]")
        console.print("项目名称只能包含字母、数字、连字符和下划线，长度2-50个字符。")
        return
    
    try:
        # 显示欢迎信息
        console.print(Panel(
            Text("🚀 SDP-PY Python项目生成器", style="bold blue"),
            subtitle=f"正在生成 {project_type} 项目: {project_name}"
        ))
        
        # 创建配置
        if config:
            project_config = ProjectConfig.load_from_file(config)
            project_config.project_name = project_name  # 命令行参数覆盖配置文件
        else:
            project_config = ConfigManager.create_default_config(project_name, project_type)
        
        # 更新配置
        project_config.update({
            'author': author,
            'email': email,
            'description': description or f"A {project_type} project generated by SDP-PY",
            'init_git': not no_git,
            'use_uv': not no_uv,
        })
        
        # 验证配置
        errors = project_config.validate()
        if errors:
            console.print("[bold red]❌ 配置验证失败：[/bold red]")
            for error in errors:
                console.print(f"  • {error}")
            return
        
        # 创建项目生成器
        generator = ProjectGenerator(project_config)
        
        # 显示项目信息
        info_table = Table(title="项目信息")
        info_table.add_column("属性", style="cyan")
        info_table.add_column("值", style="green")
        
        info_table.add_row("项目名称", project_name)
        info_table.add_row("项目类型", project_type)
        info_table.add_row("作者", author)
        info_table.add_row("邮箱", email)
        info_table.add_row("描述", project_config.description)
        info_table.add_row("目标目录", target_dir)
        info_table.add_row("初始化Git", "是" if not no_git else "否")
        info_table.add_row("使用uv", "是" if not no_uv else "否")
        
        console.print(info_table)
        console.print()
        
        # 生成项目
        success = generator.generate_project(
            project_name=project_name,
            target_dir=target_dir,
            project_type=project_type
        )
        
        if success:
            project_path = Path(target_dir) / project_name
            console.print()
            console.print(Panel(
                f"[bold green]✅ 项目生成成功！[/bold green]\n\n"
                f"项目位置: [cyan]{project_path.absolute()}[/cyan]\n\n"
                f"下一步操作：\n"
                f"  [yellow]cd {project_name}[/yellow]\n"
                f"  [yellow]uv sync[/yellow]  # 安装依赖\n"
                f"  [yellow]{'uv run uvicorn main:app --reload' if project_type == 'fastapi' else 'uv run python main.py'}[/yellow]  # 运行应用",
                title="🎉 完成",
                border_style="green"
            ))
        else:
            console.print("[bold red]❌ 项目生成失败！请检查日志文件获取详细信息。[/bold red]")
            
    except Exception as e:
        logger.error(f"项目生成异常: {str(e)}")
        console.print(f"[bold red]❌ 项目生成失败: {str(e)}[/bold red]")


@cli.command()
@click.argument('project_name')
@click.option('--type', '-t', 'project_type', 
              type=click.Choice(['fastapi', 'fastmcp']), 
              default='fastapi', help='项目类型')
@click.option('--author', '-a', default='Clark', help='作者姓名')
@click.option('--email', '-e', default='changhongyuan@126.com', help='作者邮箱')
@click.option('--description', '-d', help='项目描述')
@click.option('--target-dir', default='.', help='目标目录')
@click.option('--no-git', is_flag=True, help='不初始化Git仓库')
@click.option('--no-uv', is_flag=True, help='不初始化uv项目')
def init(
    project_name: str,
    project_type: str,
    author: str,
    email: str,
    description: Optional[str],
    target_dir: str,
    no_git: bool,
    no_uv: bool
):
    """
    初始化新的Python项目（简化命令）
    
    PROJECT_NAME: 项目名称，只能包含字母、数字、连字符和下划线
    """
    
    # 检查是否存在默认配置文件
    default_config_path = Path("project-config.yaml")
    config = None
    
    if default_config_path.exists():
        try:
            config = ProjectConfig.load_from_file(str(default_config_path))
            config.project_name = project_name  # 命令行参数覆盖配置文件
            console.print(f"[green]使用默认配置文件: {default_config_path}[/green]")
        except Exception as e:
            console.print(f"[yellow]⚠️  读取默认配置文件失败: {str(e)}，将使用默认配置[/yellow]")
            config = None
    
    # 如果没有配置文件或者读取失败，创建默认配置
    if config is None:
        config = ConfigManager.create_default_config(project_name, project_type)
    
    # 更新配置
    config.update({
        'author': author,
        'email': email,
        'description': description or config.description or f"A {project_type} project generated by SDP-PY",
        'init_git': not no_git,
        'use_uv': not no_uv,
    })
    
    # 验证项目名称
    if not ConfigManager.validate_project_name(project_name):
        console.print("[bold red]❌ 项目名称无效！[/bold red]")
        console.print("项目名称只能包含字母、数字、连字符和下划线，长度2-50个字符。")
        return
    
    try:
        # 显示欢迎信息
        console.print(Panel(
            Text("🚀 SDP-PY Python项目生成器", style="bold blue"),
            subtitle=f"正在初始化 {project_type} 项目: {project_name}"
        ))
        
        # 验证配置
        errors = config.validate()
        if errors:
            console.print("[bold red]❌ 配置验证失败：[/bold red]")
            for error in errors:
                console.print(f"  • {error}")
            return
        
        # 创建项目生成器
        generator = ProjectGenerator(config)
        
        # 显示项目信息
        info_table = Table(title="项目信息")
        info_table.add_column("属性", style="cyan")
        info_table.add_column("值", style="green")
        
        info_table.add_row("项目名称", project_name)
        info_table.add_row("项目类型", project_type)
        info_table.add_row("作者", author)
        info_table.add_row("邮箱", email)
        info_table.add_row("描述", config.description)
        info_table.add_row("目标目录", target_dir)
        info_table.add_row("初始化Git", "是" if not no_git else "否")
        info_table.add_row("使用uv", "是" if not no_uv else "否")
        info_table.add_row("使用配置文件", "是" if default_config_path.exists() else "否")
        
        console.print(info_table)
        console.print()
        
        # 生成项目
        success = generator.generate_project(
            project_name=project_name,
            target_dir=target_dir,
            project_type=project_type
        )
        
        if success:
            project_path = Path(target_dir) / project_name
            console.print()
            console.print(Panel(
                f"[bold green]✅ 项目初始化成功！[/bold green]\n\n"
                f"项目位置: [cyan]{project_path.absolute()}[/cyan]\n\n"
                f"下一步操作：\n"
                f"  [yellow]cd {project_name}[/yellow]\n"
                f"  [yellow]uv sync[/yellow]  # 安装依赖\n"
                f"  [yellow]{'uv run uvicorn main:app --reload' if project_type == 'fastapi' else 'uv run python main.py'}[/yellow]  # 运行应用",
                title="🎉 完成",
                border_style="green"
            ))
        else:
            console.print("[bold red]❌ 项目初始化失败！请检查日志文件获取详细信息。[/bold red]")
            
    except Exception as e:
        logger.error(f"项目初始化异常: {str(e)}")
        console.print(f"[bold red]❌ 项目初始化失败: {str(e)}[/bold red]")


@cli.command()
def templates():
    """列出可用的项目模板"""
    
    template_manager = TemplateManager()
    available_templates = template_manager.list_templates()
    
    console.print(Panel(
        Text("📋 可用项目模板", style="bold blue"),
        subtitle="选择适合您需求的项目类型"
    ))
    
    template_table = Table(title="项目模板")
    template_table.add_column("类型", style="cyan", width=12)
    template_table.add_column("名称", style="green", width=20)
    template_table.add_column("描述", style="white", width=40)
    template_table.add_column("主要依赖", style="yellow")
    
    for template_type in available_templates:
        info = template_manager.get_template_info(template_type)
        template_table.add_row(
            template_type,
            info.get('name', template_type),
            info.get('description', ''),
            ', '.join(info.get('dependencies', []))
        )
    
    console.print(template_table)
    
    console.print("\n[dim]使用方法：[/dim]")
    console.print("[dim]  sdp generate my-project --type fastapi[/dim]")


@cli.command()
@click.argument('project_name')
@click.option('--type', '-t', 'project_type', 
              type=click.Choice(['fastapi', 'fastmcp']), 
              default='fastapi')
@click.option('--output', '-o', default='project-config.yaml', help='输出配置文件路径')
def init_config(project_name: str, project_type: str, output: str):
    """
    生成项目配置文件
    
    PROJECT_NAME: 项目名称
    """
    
    try:
        # 创建默认配置
        config = ConfigManager.create_default_config(project_name, project_type)
        
        # 保存配置文件
        config.save_to_file(output)
        
        console.print(f"[green]✅ 配置文件已生成: {output}[/green]")
        console.print(f"[dim]编辑配置文件后，使用以下命令生成项目：[/dim]")
        console.print(f"[dim]  sdp generate {project_name} --config {output}[/dim]")
        
    except Exception as e:
        console.print(f"[bold red]❌ 配置文件生成失败: {str(e)}[/bold red]")


@cli.command()
def version():
    """显示版本信息"""
    
    from core import __version__, __author__, __description__
    
    console.print(Panel(
        f"[bold blue]SDP-PY[/bold blue] v{__version__}\n\n"
        f"[dim]{__description__}[/dim]\n\n"
        f"作者: {__author__}\n"
        f"GitHub: https://github.com/your-org/sdp-py",
        title="版本信息"
    ))


def generate_project(project_name: str, **kwargs):
    """
    程序化接口：生成项目
    
    Args:
        project_name: 项目名称
        **kwargs: 其他配置参数
    """
    config = ConfigManager.create_default_config(project_name, kwargs.get('project_type', 'fastapi'))
    config.update(kwargs)
    
    generator = ProjectGenerator(config)
    return generator.generate_project(
        project_name=project_name,
        target_dir=kwargs.get('target_dir', '.'),
        project_type=kwargs.get('project_type', 'fastapi')
    )


if __name__ == '__main__':
    # 确保日志目录存在
    Path('logs').mkdir(exist_ok=True)
    
    # 运行CLI
    cli()